import { reqCartList, reqDeleteCartById,reqUpdateCheckedByid } from "@/api"
import { Promise } from "core-js"

const state = {
    cartList:[]
}
const mutations = {
    GETCARTLIST(state, cartList) { 
        state.cartList = cartList
    }
}
const actions = {
    //获取购物车列表的数据
   async getCartList({ commit }) { 
        let result = await reqCartList()
        //测试是否可以获取购物车的数据
        if (result.code == 200) { 
            commit('GETCARTLIST',result.data)
        }

    },
    //删除购物车某一个产品
   async deleteCartListBySkuId({ commit }, skuId) { 
       let result = await reqDeleteCartById(skuId)
       if (result.code == 200) {
           return 'ok'
       } else { 
           return Promise(new Error('faile'))
       }
    },
   //修改购物车某一产品选中状态
    async updateCheckedById({ commit }, { skuId, isChecked }) { 
        let result = await reqUpdateCheckedByid(skuId, isChecked)
        if (result.code == 200) {
            return 'ok'
        } else { 
            return Promise.reject(new Error('faile'))
        }
    },
    //删除全部勾选的产品  利用actions扩展 context
    //context 小仓库 commit(提交mutations修改state) getters
    deleteAllCheckedCart({ dispatch, getters }) {
        //删除选中的所有商品
         let PromiseAll = []
         getters.cartList.cartInfoList.forEach(item =>  {
             
                //将每一次返回值添加到数组中
              let promise = item.isChecked === 1?dispatch('deleteCartListBySkuId',item.skuId):''
              PromiseAll.push(promise)
         })
           return Promise.all(PromiseAll)
        //Promise.all([p1,p2,p3])  每一个p1都是一个Promise对象 如果有一个失败 都失败 
        //都成功 返回的结果即为成功
    },
    //修改全部产品的选中状态
    updateAllCartIsChecked({ dispatch, state}, isChecked) {
        let promiseAll = []
        state.cartList[0].cartInfoList.forEach(item => { 
            let promise = dispatch('updateCheckedById', { skuId: item.skuId, isChecked })
            promiseAll.push(promise)
        })
        //最终返回结果
        return Promise.all(promiseAll)
    }
}
const getters = {
    cartList(state) {
        return state.cartList[0] ||{}

    },
   

}
export default {
    state,
    mutations,
    actions,
    getters
}